/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

import dao.ContatoDAO;
import java.util.Vector;
import javax.microedition.lcdui.Alert;
import javax.microedition.lcdui.Choice;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.Image;
import javax.microedition.lcdui.Item;
import javax.microedition.lcdui.List;
import javax.microedition.lcdui.TextField;
import javax.microedition.midlet.*;
import model.Contato;
import org.netbeans.microedition.lcdui.SplashScreen;
import util.Constants;

/**
 * @author Luciano
 */
public class Main extends MIDlet implements CommandListener{

    public ContatoDAO dao = new ContatoDAO();
    private Vector contatos = new Vector();
    private boolean midletPaused = false;
    
    private List list;
    private Form frIncluirContato;
    private TextField fone;
    private TextField celular;
    private TextField nome;
    private TextField email;
    private List listaContatos;
    private Alert alert;
    private Form frPesquisa;
    private TextField tfPesquisa;
    private SplashScreen splashScreen;
    private Command IncluirContato;
    private Command alterarContato;
    private Command itemCommand1;
    private Command exitCommand;
    private Command okCommand;
    private Command backCommand;
    private Command backCommand1;
    private Image image3;
    private Image image4;
    private Image image1;
    private Image image2;
    private Image image;
    private Image image5;
    private Image image6;                   

    public void startMIDlet() {                                      
        switchDisplayable(null, getSplashScreen());                                        
    }   
    public void switchDisplayable(Alert alert, Displayable nextDisplayable) {                                            
        Display display = getDisplay();                                               
        if (alert == null) {
            display.setCurrent(nextDisplayable);
        } else {
            display.setCurrent(alert, nextDisplayable);
        }                                             
    }                                   

    public void commandAction(Command command, Displayable displayable) {                                               
        if (displayable == frIncluirContato) {                                           
            if (command == backCommand) {                                         
                getNome().setConstraints(TextField.ANY);
                getFone().setConstraints(TextField.ANY);
                getCelular().setConstraints(TextField.ANY);
                getEmail().setConstraints(TextField.ANY);
                switchDisplayable(null, getList());                                           
                
            } else if (command == okCommand) {                                          
                Contato contato = new Contato();
                contato.setNome(getNome().getString());
                contato.setFone(getFone().getString());
                contato.setCelular(getCelular().getString());
                contato.setEmail(getEmail().getString());
                
                if (getFrIncluirContato().getTitle().equals(Constants.FR_INCLUI_CONTATO)) {
                    contato.setId(dao.getId());

                    try {
                        contato.isValid();
                        dao.salvarContato(contato);

                        getAlert().setString("Contato inserido com sucesso");
                        switchDisplayable(getAlert(), getFrIncluirContato());
                        setFormContato("", "", "", "");

                    } catch (Exception e) {
                        getAlert().setString(e.getMessage());
                        switchDisplayable(getAlert(), getFrIncluirContato());
                    }

                } else if (getFrIncluirContato().getTitle().equals(Constants.FR_ALTERA_CONTATO)) {
                    Contato old = (Contato) contatos.elementAt(getListaContatos().getSelectedIndex());
                    contato.setId(old.getId());

                    try {
                        contato.isValid();
                        dao.atualizaContato(contato);

                        getAlert().setString("Contato inserido com sucesso");
                        switchDisplayable(getAlert(), getFrIncluirContato());
                        setFormContato("", "", "", "");

                    } catch (Exception e) {
                        getAlert().setString(e.getMessage());
                        switchDisplayable(getAlert(), getList());
                    }
                } else if (getFrIncluirContato().getTitle().equals(Constants.FR_EXCLUI_CONTATO)) {
                    Contato old = (Contato) contatos.elementAt(getListaContatos().getSelectedIndex());
                    dao.excluiContato(old.getId());
                    switchDisplayable(null, getList());
                }

                getNome().setConstraints(TextField.ANY);
                getFone().setConstraints(TextField.ANY);
                getCelular().setConstraints(TextField.ANY);
                getEmail().setConstraints(TextField.ANY);
                switchDisplayable(null, getList());
                
            }                                           
        } else if (displayable == frPesquisa) {
            if (command == backCommand) {                                         
                switchDisplayable(null, getList());                                           
            } else if (command == okCommand) {                                          
                contatos = dao.pesquisaContato(getTfPesquisa().getString());
                if (contatos.size() > 0) {
                    getListaContatos().setTitle(Constants.FR_PESQUISA_CONTATO);
                    getListaContatos().deleteAll();//quando atualiza precisa redesenhar toda a lista
                    for (int i = 0; i < contatos.size(); i++) {
                        Contato contato = (Contato) contatos.elementAt(i);
                        getListaContatos().append(contato.getNome(), null);
                    }
                    switchDisplayable(null, getListaContatos());
                } else {
                    getAlert().setString("Registro não encontrado.");
                    switchDisplayable(getAlert(), getFrPesquisa());
                }
                                           
            }                                           
        } else if (displayable == list) {
            if (command == List.SELECT_COMMAND) {                                         
                listAction();                                            
            } else if (command == exitCommand) {                                           
                exitMIDlet();                                            
            }                                            
        } else if (displayable == listaContatos) {
            if (command == List.SELECT_COMMAND) {                                          
                listaContatosAction();                                            
            } else if (command == backCommand) {                                           
                switchDisplayable(null, getList());                                            
            }                                            
        } else if (displayable == splashScreen) {
            if (command == SplashScreen.DISMISS_COMMAND) {                                          
                switchDisplayable(null, getList());                                            
            }                                                   
        }                                                 
    }                                
             
    public List getList() {
        if (list == null) {                                 
            list = new List("Menu", Choice.IMPLICIT);                                    
            list.append("Incluir Contato", getImage1());
            list.append("Alterar Contato", getImage2());
            list.append("Excluir Contato", getImage3());
            list.append("Pesquisar Contato", getImage4());
            list.append("Encerrar", getImage5());
            list.addCommand(getExitCommand());
            list.setCommandListener(this);
            list.setSelectedFlags(new boolean[] { false, false, false, false, false });                                  
        }                         
        return list;
    }
     
    public void listAction() {                                   
        String __selectedString = getList().getString(getList().getSelectedIndex());                                     
        if (__selectedString != null) {
            if (__selectedString.equals("Incluir Contato")) {                                   

                getFrIncluirContato().setTitle(Constants.FR_INCLUI_CONTATO);
                setFormContato("", "", "", "");
                switchDisplayable(null, getFrIncluirContato());                                     
            } else if (__selectedString.equals("Alterar Contato")) {                                    

                getFrIncluirContato().setTitle(Constants.FR_ALTERA_CONTATO);
                getListaContatos().setTitle(Constants.FR_ALTERA_CONTATO);
                contatos = dao.listaContatos();
                getListaContatos().deleteAll();//quando atualiza precisa redesenhar toda a lista
                for (int i = 0; i < contatos.size(); i++) {
                    Contato contato = (Contato) contatos.elementAt(i);
                    getListaContatos().append(contato.getNome(), null);
                }
                switchDisplayable(null, getListaContatos());                                     
            } else if (__selectedString.equals("Excluir Contato")) {                                    
                getFrIncluirContato().setTitle(Constants.FR_EXCLUI_CONTATO);
                getListaContatos().setTitle(Constants.FR_EXCLUI_CONTATO);

                contatos = dao.listaContatos();
                getListaContatos().deleteAll();//quando atualiza precisa redesenhar toda a lista
                for (int i = 0; i < contatos.size(); i++) {
                    Contato contato = (Contato) contatos.elementAt(i);
                    getListaContatos().append(contato.getNome(), null);
                }
                switchDisplayable(null, getListaContatos());
                                     
                getNome().setConstraints(TextField.UNEDITABLE);
                getFone().setConstraints(TextField.UNEDITABLE);
                getCelular().setConstraints(TextField.UNEDITABLE);
                getEmail().setConstraints(TextField.UNEDITABLE);
                
            } else if (__selectedString.equals("Pesquisar Contato")) {
                
                getNome().setConstraints(TextField.ANY);
                getFone().setConstraints(TextField.ANY);
                getCelular().setConstraints(TextField.ANY);
                getEmail().setConstraints(TextField.ANY);
                
                getFrPesquisa().setTitle(Constants.FR_PESQUISA_CONTATO);
                getListaContatos().setTitle(Constants.FR_PESQUISA_CONTATO);
                getFrIncluirContato().setTitle(Constants.FR_ALTERA_CONTATO);
                contatos.removeAllElements();
                switchDisplayable(null, getFrPesquisa());                                     
            } else if (__selectedString.equals("Encerrar")) {                                    
                exitMIDlet();                                      
            }                                       
        }                                     
    }                          
       
    public Command getIncluirContato() {
        if (IncluirContato == null) {                                 
            IncluirContato = new Command("Incluir Contato", Command.ITEM, 0);                                   
        }                         
        return IncluirContato;
    }
      
    public Command getAlterarContato() {
        if (alterarContato == null) {                                 
            alterarContato = new Command("Item", Command.ITEM, 0);                                   
        }                         
        return alterarContato;
    }
      
    public Command getItemCommand1() {
        if (itemCommand1 == null) {                                 
            itemCommand1 = new Command("Item", Command.ITEM, 0);                                   
        }                         
        return itemCommand1;
    }
      
    public Command getExitCommand() {
        if (exitCommand == null) {                                 
            exitCommand = new Command("Sair", Command.EXIT, 0);                                   
        }                         
        return exitCommand;
    }

    public Image getImage1() {
        if (image1 == null) {                                 
            try {                                                
                image1 = Image.createImage("/images/incluirContato.png");
            } catch (java.io.IOException e) {                                              
                e.printStackTrace();
            }                                   
        }                         
        return image1;
    }
      
    public Image getImage2() {
        if (image2 == null) {                                 
            try {                                                
                image2 = Image.createImage("/images/alterarContato.png");
            } catch (java.io.IOException e) {                                              
                e.printStackTrace();
            }                                   
        }                         
        return image2;
    }
      
    public Image getImage3() {
        if (image3 == null) {                                 
            try {                                                
                image3 = Image.createImage("/images/excluirContato.png");
            } catch (java.io.IOException e) {                                              
                e.printStackTrace();
            }                                   
        }                         
        return image3;
    }
      
    public Image getImage4() {
        if (image4 == null) {                                 
            try {                                                
                image4 = Image.createImage("/images/pesquisarContato.png");
            } catch (java.io.IOException e) {                                              
                e.printStackTrace();
            }                                   
        }                         
        return image4;
    }
      
    public Form getFrIncluirContato() {
        if (frIncluirContato == null) {                                 
            frIncluirContato = new Form("Incluir Contato", new Item[] { getNome(), getFone(), getCelular(), getEmail() });                                    
            frIncluirContato.addCommand(getBackCommand());
            frIncluirContato.addCommand(getOkCommand());
            frIncluirContato.setCommandListener(this);                                  
        }                         
        return frIncluirContato;
    }
      
    public TextField getNome() {
        if (nome == null) {                                 
            nome = new TextField("Nome", null, 50, TextField.ANY);                                   
        }                         
        return nome;
    }

    public TextField getFone() {
        if (fone == null) {                                 
            fone = new TextField("Fone", null, 8, TextField.ANY);                                   
        }                         
        return fone;
    }
      
    public TextField getCelular() {
        if (celular == null) {                                 
            celular = new TextField("Celular", null, 8, TextField.ANY);                                   
        }                         
        return celular;
    }
      
    public TextField getEmail() {
        if (email == null) {                                 
            email = new TextField("E-mail", null, 50, TextField.ANY);                                   
        }                         
        return email;
    }
      
    public Command getBackCommand() {
        if (backCommand == null) {                                 
            backCommand = new Command("Voltar", Command.BACK, 0);                                   
        }                         
        return backCommand;
    }
      
    public Command getOkCommand() {
        if (okCommand == null) {                                 
            okCommand = new Command("OK", Command.OK, 0);                                   
        }                         
        return okCommand;
    }
      
    public List getListaContatos() {
        if (listaContatos == null) {                                 
            listaContatos = new List("list1", Choice.IMPLICIT);                                    
            listaContatos.addCommand(getBackCommand());
            listaContatos.setCommandListener(this);                                  

        }                         
        return listaContatos;
    }
      
    public void listaContatosAction() {                                   
        String __selectedString = getListaContatos().getString(getListaContatos().getSelectedIndex());                                     
        Contato contato = (Contato) contatos.elementAt(getListaContatos().getSelectedIndex());
        getNome().setString(contato.getNome());
        getFone().setString(contato.getFone());
        getCelular().setString(contato.getCelular());
        getEmail().setString(contato.getEmail());

        switchDisplayable(null, getFrIncluirContato());
    }                         

    public Command getBackCommand1() {
        if (backCommand1 == null) {                                 
            backCommand1 = new Command("Voltar", Command.BACK, 0);                                   
        }                         
        return backCommand1;
    }
      
    public Image getImage() {
        if (image == null) {                                 
            try {                                                
                image = Image.createImage("/images/sair.png");
            } catch (java.io.IOException e) {                                              
                e.printStackTrace();
            }                                   
        }                         
        return image;
    }
      
    public Image getImage5() {
        if (image5 == null) {                                 
            try {                                                
                image5 = Image.createImage("/images/sair.png");
            } catch (java.io.IOException e) {                                              
                e.printStackTrace();
            }                                   
        }                         
        return image5;
    }
      
    public Alert getAlert() {
        if (alert == null) {                                 
            alert = new Alert("alert");                                    
            alert.setTimeout(Alert.FOREVER);                                  
        }                         
        return alert;
    }
      
    public Form getFrPesquisa() {
        if (frPesquisa == null) {                                 
            frPesquisa = new Form("form", new Item[] { getTfPesquisa() });                                    
            frPesquisa.addCommand(getOkCommand());
            frPesquisa.addCommand(getBackCommand());
            frPesquisa.setCommandListener(this);                                  
        }                         
        return frPesquisa;
    }
      
    public TextField getTfPesquisa() {
        if (tfPesquisa == null) {                                 
            tfPesquisa = new TextField("Nome", null, 32, TextField.ANY);                                   
        }                         
        return tfPesquisa;
    }
      
    public SplashScreen getSplashScreen() {
        if (splashScreen == null) {                                 
            splashScreen = new SplashScreen(getDisplay());                                    
            splashScreen.setTitle("Agendinha");
            splashScreen.setCommandListener(this);
            splashScreen.setImage(getImage6());
        }                         
        return splashScreen;
    }
      
    public Image getImage6() {
        if (image6 == null) {                                 
            try {                                                
                image6 = Image.createImage("/images/iphone-contacts.png");
            } catch (java.io.IOException e) {                                              
                e.printStackTrace();
            }                                   
        }                         
        return image6;
    }
      
    public Display getDisplay() {
        return Display.getDisplay(this);
    }

    public void exitMIDlet() {
        switchDisplayable(null, null);
        destroyApp(true);
        notifyDestroyed();
    }

    public void startApp() {
        if (midletPaused) {
    //        resumeMIDlet();
        } else {
        //    initialize();
            startMIDlet();
        }
        midletPaused = false;
    }

    public void pauseApp() {
        midletPaused = true;
    }

    public void destroyApp(boolean unconditional) {
    }

    public void setFormContato(String nome, String fone, String celular, String email) {
        getNome().setString(nome);
        getFone().setString(fone);
        getCelular().setString(celular);
        getEmail().setString(email);
    }

}
